// created by noellynch
// May 17, 2011

package com.gruntdb.engines.indexedjson;

import java.io.File;


import com.gruntdb.core.GruntDataStore;
import com.gruntdb.core.stubs.IGruntDBIndex;
import com.gruntdb.core.stubs.IStorageEngine;
import com.gruntdb.core.stubs.IStorageValue;
import com.gruntdb.objects.GruntDBIndexIterator;
import com.gruntdb.objects.GruntDBIndexStore;
import com.gson4javaext.core.GSON4JavaExt;

public class IndexedJSONStorageEngine implements IStorageEngine {
	private		IndexedJSONStorageProperties		mcl_properties;
	private		GruntDBIndexStore					mcl_indexStore;
	private		IndexedJSONStoreManager				mcl_segmentMgr;
	
	private		GruntDataStore		mcl_dataStore;
	
	private		File		mcl_location;
	
	public	IndexedJSONStorageEngine() {
		mcl_properties = new IndexedJSONStorageProperties(this);
		mcl_indexStore = new GruntDBIndexStore(this);
		mcl_segmentMgr = new IndexedJSONStoreManager(this);
	}
	
	@Override
	public long add(Object cl_value) {
		// get the next id
		long		ll_nextID = mcl_indexStore.getNextPossibleID();
		
		// transform value
		String		lstr_json = GSON4JavaExt.toJsonString(cl_value);
		
		// save the value out to the segment file and return the newly created index
		IGruntDBIndex		lcl_gid = mcl_segmentMgr.saveToSegment(ll_nextID, lstr_json);
		
		// now save this index in the index store
		try {
			// if there is no space for more indices allocate more space
			if(!mcl_indexStore.isSpaceForNewIndex()) {
				mcl_indexStore.allocateNewBlock();
			}
			
			// add the index
			mcl_indexStore.addNewIndex(lcl_gid);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// return newly created id..
		return lcl_gid.getId();
	}

	@Override
	public IStorageValue get(long lIndex) {
		return null;
	}

	@Override
	public void initialise(GruntDataStore cl_dataStore) {
		mcl_dataStore = cl_dataStore;
		mcl_properties.loadDataStoreProperties();
		//mcl_indexStore.initFromProperties();
		mcl_indexStore.initIndexFile();
		mcl_segmentMgr.initialise();;
	}

	@Override
	public File getLocation() {
		if(mcl_location == null) {
			mcl_location = new File(mcl_dataStore.getLocation());
		}
		return mcl_location;
	}

	@Override
	public String getFileReferenceName() {
		return mcl_dataStore.getFileReferenceName();
	}
	
	public	IndexedJSONStorageProperties		getProperties() {
		return mcl_properties;
	}
	
	protected	GruntDBIndexStore		getIndexStore() {
		return mcl_indexStore;
	}
	
	protected	IndexedJSONStoreManager		getSegmentManager() {
		return mcl_segmentMgr;
	}
	
	@Override
	public	void	close() {
		mcl_indexStore.close();
		mcl_properties.close();
	}

	@Override
	public long getSizeofIndex() {
		return IndexedJSONStorageIndex.sizeofInBytes();
	}

	@Override
	public Class getIndexType() {
		return IndexedJSONStorageIndex.class;
	}

	@Override
	public GruntDBIndexIterator getIndexIterator() {
		return mcl_indexStore.iterator();
	}
	
	

}
